package com.wfm.files.bio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NioFileProcessor {
    public static void main(String[] args) {
        Path inputFile = Paths.get("input.txt"); // 文件 A 的路径
        Path outputFile = Paths.get("output.txt"); // 文件 B 的路径

        try (FileChannel inputChannel = FileChannel.open(inputFile, StandardOpenOption.READ);
             FileChannel outputChannel = FileChannel.open(outputFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

            ByteBuffer buffer = ByteBuffer.allocate(1024); // 分配一个缓冲区
            StringBuilder content = new StringBuilder();

            while (inputChannel.read(buffer) != -1) { // 从输入通道读取数据
                buffer.flip(); // 切换到读模式
                while (buffer.hasRemaining()) {
                    char c = (char) buffer.get(); // 逐字节读取
                    if (c == '\n' || c == '\r') {
                        // 删除前一个逗号
                        if (content.length() > 0 && content.charAt(content.length() - 1) == ',') {
                            content.setLength(content.length() - 1);
                        }
                        content.append(c); // 保留换行符
                    } else {
                        content.append(c).append(","); // 在每个字符后添加逗号
                    }
                }
                buffer.clear(); // 清空缓冲区，准备下一次读取
            }


            // 将处理后的内容写入输出通道
            ByteBuffer outputBuffer = ByteBuffer.wrap(content.toString().getBytes());
            while (outputBuffer.hasRemaining()) {
                outputChannel.write(outputBuffer);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}